// Created: Dec 11, 2014
//
// Author: wjinwen.1988@gmail.com

#include "chi/thread.h"

#include <assert.h>
#include <iostream>

#include <glog/logging.h>

namespace chi {

Thread::Thread(const ThreadFunc& func, const std::string& name)
  : started_(false),
    joined_(false),
    pthreadid_(0),
    func_(func),
    name_(name) { 
}

Thread::~Thread() {
  if (started_ && !joined_) {
    pthread_detach(pthreadid_);
  }
}

void Thread::Start() {
  assert(!started_);
  started_ = true;
  if (pthread_create(&pthreadid_, NULL, &Thread::StartThread, this)) {
    started_ = false;
    LOG(ERROR) << "Failed in pthread_create";
  }
}

int Thread::Join()
{
  assert(started_);
  assert(!joined_);
  joined_ = true;
  return pthread_join(pthreadid_, NULL);
}

void* Thread::StartThread(void *arg) {
  Thread* thread = static_cast<Thread*>(arg);
  thread->RunInThread();
  return NULL;
}

void Thread::RunInThread() { func_(); }

}  // namespace chi 
